/**
 * Created by chenweicheng on 19/6/18.
 */
/**
 * Created by chenweicheng on 15/7/17.
 */
import React, {PureComponent} from 'react'
import {
    View,
    Text,
    StyleSheet,
    Image,
    TouchableOpacity,
    NativeAppEventEmitter,
    Platform,
    Alert,
    TextInput,
    ScrollView
} from 'react-native'

import {NavigationActions} from 'react-navigation'
import {px2dpH, px2dpW} from '../config/px2dp'
import theme from '../config/theme'
import ModalDialog from '../widget/ModalDialog'
import ModalListDialog from '../widget/ModalListDialog'
import  ProtobufJsManager from "../proto/ProtobufJsManager"
import net from 'net';

import  UtilManager from "../util/UtilManager"
import  TcpManager from "../manager/TcpManager"
import  MsgManager from "../manager/MsgManager"
export  default class GetDataScene extends PureComponent {
    static navigationOptions = ({navigation}) => ({

        headerTitle: '获取数据',

        headerRight: <View/>,
        headerStyle: theme.headerStyle,


    });


    constructor() {
        super();

        this.state = {
            reload: false
        }
        this.ssid = "";
        this.wifipswd = "";

        this.ip = ""
        this.port = "";
        this.chatter = [];
        this.updateChatter = this.updateChatter.bind(this);

        this.tcpsend = ""
    }

    reload() {
        this.setState({reload: !this.state.reload})
    }


    componentWillMount() {


    }
    componentWillUnmount() {
        this.camera = null;

    }


    componentWillUnmount() {
        this.unsub()
        NativeAppEventEmitter.emit('gobacktohome', 'gobacktohome')
    }


    updateChatter(msg) {

        this.chatter = this.chatter.concat([msg])
        this.reload()

    }

    sub() {
        this._fousListener = this.props.navigation.addListener('didFocus', () => {
            console.log("_fousListener")


        });
        this._blurListener = this.props.navigation.addListener('willBlur', () => {
            console.log("_blurListener")
        });
    }

    unsub() {
        this._fousListener.remove();
        this._blurListener.remove();
    }

    componentDidMount() {

        this.sub()


        UtilManager.getWifiConnectedSsid().then((data) => {
            console.log("success", data)
            this.ssid = data
            this.reload()
        }, (error) => {
            this.ssid = '';
            console.log("fail", error)
        })


    }

    SnapConfig() {
        // if (this.ssid != "" && this.wifipswd != "") {
        //
        //     let SnapMsg = ProtobufJsManager.getProtoMessage(ProtobufJsManager.headerType.SnapApp);
        //     //根据实际情况set
        //     let snapconfig = {SSID: this.ssid, password: this.wifipswd}
        //
        //     let loopcount = ProtobufJsManager.getLoopCount();
        //
        //     let data = {
        //         loopCount: loopcount,
        //         timestamp: new Date().getTime() + "",
        //         type: 4,
        //         config: snapconfig
        //     };
        //
        //
        //     console.log('SnapConfig DATA', data);
        //     let message = SnapMsg.create(data);
        //
        //
        //     //生成一个SnapMsg消息
        //     ProtobufJsManager.createMessage(message, ProtobufJsManager.headerType.SnapApp).then((createMsg) => {
        //         //生成的消息
        //         console.log("create message success:" + createMsg);
        //
        //         // ProtobufJsManager.parseMessage(createMsg, ProtobufJsManager.headerType.SnapApp).then((result) => {
        //         //     console.log('GET DATA RESULT FROM DEVICE', result);
        //         // }, (error) => {
        //         //     console.log("error=" + error)
        //         // });
        //         this.tcpsend = createMsg
        //         this.reload()
        //
        //     }, (error) => {
        //         console.log("create message fail:" + error)
        //     });
        // } else {
        //     alert("wifi or pswd blank")
        // }

        MsgManager.SnapConfig(this.ssid, this.wifipswd).then((result) => {
            this.tcpsend = result.msg
            this.reload()
            console.log(result.loopcount, result.msg)
        }, (fail) => {
            alert(fail)
        })

    }

    clientConnect(sn) {
        console.log(this.ip, this.port)
        // let client = net.createConnection({host: this.ip, port: this.port}, () => {
        //     this.updateChatter('opened client on ' + JSON.stringify(client.address()));
        //   //  client.write('Hello, server! Love, Client.');
        //     this.tcpready=true;
        // });
        TcpManager.clientConnect(this.ip, this.port, sn).then((client) => {
            this.client = client
        }, (error) => {
            console.log("client tcp error", error)
        })

        //TcpManager.client.on('data', this.ondata.bind(this));

        // this.client.destroy(); // kill client after server's response
        // this.server.close();
        // TcpManager.client.on('error', (error) => {
        //     this.updateChatter('client error ' + error);
        //     //this.tcpready = false
        // });
        //
        // TcpManager.client.on('close', () => {
        //     this.updateChatter('client close');
        //     //this.tcpready = false
        // });

        //   this.client = client;
    }

    ondata(zz) {

        console.log("Getdatascene  Received:", zz)
        this.updateChatter('Getdatascene  Received: ' + zz);
    }

    send() {
        //TcpManager.client.write(this.tcpsend);
    }

    onchangeip(text) {
        this.ip = text + ""
        //  console.log("onchangeip", this.ip)


    }

    onchangeport(text) {
        this.port = text
        //console.log("onchangeip", this.port)

    }

    onchangewifipswd(text) {
        this.wifipswd = text
        //console.log("onchangewifipswd", this.wifipswd)

    }

    ontcpsend(text) {
        this.tcpsend = text
        // console.log("ontcpsend", this.tcpsend)

    }

    testtest() {

        // ProtobufJsManager.parseMessage("0801120d31353330383637333434383336180422130a0751526f7574657212087174687771746877".replace(" ", ""), ProtobufJsManager.headerType.SnapApp).then((result) => {
        //     console.log('GET DATA RESULT FROM DEVICE', result);
        // }, (error) => {
        //     console.log("error=" + error)
        // });

        MsgManager.getData(1).then((result) => {
            console.log("getdata", result.loopcount, result.msg)

        }, (fail) => {
            alert(fail)
        })
        MsgManager.getDataEnv(1).then((result) => {
            console.log("getdata env", result.loopcount, result.msg)

        }, (fail) => {
            alert(fail)
        })
    }

    connectToApTcp() {


        // this.ssid = "QRouter"
        // this.wifipswd = 'qthwqthw'
        if (this.ssid == "" || this.wifipswd == "") {
            alert("请先完成第一步")
            return
        }
        //判断是否已经连上指定wifi


        UtilManager.getWifiConnectedSsid().then((data) => {
            console.log("success", data)
            //this.ssid = data
            // this.reload()
            if (data == "ESP8266_WIFI\u0000") {
                //连上wifi后开始连接tcp

                //let client = TcpManager.clientConnect("192.168.1.1", 9123)
                TcpManager.clientConnect("192.168.1.1", 9123, "").then((client) => {
                    this.client = client
                    if (TcpManager.tcpReady) {
                        //连上tcp后发送消息 将ssid和pswd发送过去//todo  这里好像说回复我什么
                        console.log("tcpReady true")


                        MsgManager.SnapConfig(this.ssid, this.wifipswd).then((result) => {
                            this.tcpsend = result.msg
                            this.reload()
                            console.log(result.loopcount, result.msg)


                            TcpManager.send(result.loopcount, result.msg, (data) => {
                                console.log("send ssid and pswd callback", data)

                                //   { loopCount: 1, type: 4, ret: 1 }
                                if (data.type == 4 && data.ret == 1) {
                                    alert("配网成功，请连接所配置路由后点击监听按钮")

                                }
                            },false);


                            //拿到ssid和pswd后设备重启，模式由ap模式变为sta模式，开始连接路由

                            //App udp 监听9124，获取设备sn和ip  // todo 这里sn我事先会知道吗？

                            // 拿到ip后，连接tcp 的ip 和9123端口，此是成功连接设备，可以开始发送消息  需要保存sn和ip以及连接状态在tcp manager里


                        }, (fail) => {
                            alert(fail)
                        })


                    } else {
                        console.log("tcpReady false")


                    }

                }, (error) => {
                    console.log("client tcp error", error)
                })


                //  this.timeout && clearTimeout(this.timeout)
                //  this.timeout = setTimeout(() => {

                //   }, 500)


            } else {
                alert("请先连接ap模式的热点")
            }

        }, (error) => {
            this.ssid = '';
            console.log("fail", error)
        })


    }

    refresh() {
        UtilManager.getWifiConnectedSsid().then((data) => {
            console.log("success", data)
            this.ssid = data
            this.reload()
        }, (error) => {
            this.ssid = '';
            console.log("fail", error)
        })
    }


    startGetIpAndSn() {
        //todo  这里要加loading
        UtilManager.receiveSpecLenByte(9331, 60000, 0).then((callback) => {
            //'#3:192.168.001.135&mysncode'
            console.log("receiveSpecLenByte suc", callback)
            let split1 = callback.split("&")
            let sn = split1[1]
            let ip = split1[0].substring(3, split1[0].length)

            console.log("sn", sn)
            console.log("ip", ip)


            //   let client = TcpManager.clientConnect(ip, 9123)


            TcpManager.clientConnect(ip, 9123, sn).then((client) => {
                this.client = client
                if (TcpManager.tcpReady) {
                    console.log("tcpReady true")

                    alert("配置成功")


                } else {
                    console.log("tcpReady false")

                }
            }, (error) => {
                console.log("client tcp error", error)
            })
            //this.timeout && clearTimeout(this.timeout)
            //   this.timeout = setTimeout(() => {

            //   }, 500)


        }, (error) => {
            console.log("receiveSpecLenByte fail", error)
        })
    }

    getDataList() {


        MsgManager.getDataList().then((result) => {
            this.tcpsend = result.msg
            this.reload()
            console.log(result.loopcount, result.msg)

            if (TcpManager.tcpReady) {
                console.log("tcpReady true")
                TcpManager.send(result.loopcount, result.msg, (data) => {
                    console.log("getdatalist callback", data)

                },false);
            } else {
                console.log("tcpReady false")

            }

        }, (fail) => {
            alert(fail)
        })


    }

    render() {

        return (
            <View style={styles.container}>
                <Text> 1、请先连接设备将要连接的热点，并填入密码</Text>
                <View style={{width:px2dpW(240),height: 40,justifyContent:'center'}}>
                    <TextInput
                        style={{width:px2dpW(240),height: 40, borderColor: 'gray', borderWidth: 1}}
                        editable={false}
                        defaultValue={this.ssid}
                        underlineColorAndroid={"transparent"}
                        placeholder={"wifi"}
                    />
                    <TouchableOpacity style={{position:"absolute",right:10}} onPress={this.refresh.bind(this)}>
                        <Text>刷新</Text>
                    </TouchableOpacity>
                </View>

                <TextInput
                    style={{width:px2dpW(240),height: 40, borderColor: 'gray', borderWidth: 1}}
                    onChangeText={this.onchangewifipswd.bind(this)}
                    defaultValue={this.wifipswd}
                    underlineColorAndroid={"transparent"}
                    placeholder={"wifi password"}
                />
                <Text> 2、请长按设备进入AP模式,然后手机连接wifi XXXXXXXXX,连接完成后点击下一步</Text>

                <TouchableOpacity onPress={this.connectToApTcp.bind(this)}
                                  style={{height:50,width:120,backgroundColor:'#eeeeee',alignItems:'center',justifyContent:'center',margin:5}}>
                    <Text> 下一步</Text>
                </TouchableOpacity>
                <TouchableOpacity onPress={this.startGetIpAndSn.bind(this)}
                                  style={{height:50,width:120,backgroundColor:'#eeeeee',alignItems:'center',justifyContent:'center',margin:5}}>
                    <Text>监听</Text>
                </TouchableOpacity>
                {/*<TouchableOpacity onPress={this.getDataList.bind(this)}*/}
                                  {/*style={{height:50,width:120,backgroundColor:'#eeeeee',alignItems:'center',justifyContent:'center',margin:5}}>*/}
                    {/*<Text> 查询数据列表</Text>*/}
                {/*</TouchableOpacity>*/}
                {/*<Text onPress={this.SnapConfig.bind(this)} style={{fontSize:20}}>生成配置消息</Text>*/}
                {/*<TextInput*/}
                    {/*style={{width:px2dpW(240),height: 40, borderColor: 'gray', borderWidth: 1}}*/}
                    {/*onChangeText={this.onchangeip.bind(this)}*/}
                    {/*defaultValue={this.ip}*/}
                    {/*underlineColorAndroid={"transparent"}*/}
                    {/*placeholder={"ip"}*/}
                {/*/>*/}
                {/*<TextInput*/}
                    {/*style={{width:px2dpW(240),height: 40, borderColor: 'gray', borderWidth: 1}}*/}
                    {/*onChangeText={this.onchangeport.bind(this)}*/}
                    {/*defaultValue={this.port}*/}
                    {/*underlineColorAndroid={"transparent"}*/}
                    {/*placeholder={"port"}*/}
                {/*/>*/}
                {/*<TouchableOpacity onPress={this.clientConnect.bind(this)}*/}
                {/*style={{height:50,width:120,backgroundColor:'#eeeeee',alignItems:'center',justifyContent:'center',margin:5}}>*/}
                {/*<Text> connect client</Text>*/}
                {/*</TouchableOpacity>*/}


                {/*<TextInput*/}
                    {/*style={{width:px2dpW(240),height: 40, borderColor: 'gray', borderWidth: 1}}*/}
                    {/*onChangeText={this.ontcpsend.bind(this)}*/}
                    {/*defaultValue={this.tcpsend}*/}
                    {/*underlineColorAndroid={"transparent"}*/}
                    {/*placeholder={"tcpsend"}*/}
                {/*/>*/}
                {/*<TouchableOpacity onPress={this.send.bind(this)}*/}
                                  {/*style={{height:50,width:120,backgroundColor:'#eeeeee',alignItems:'center',justifyContent:'center',margin:5}}>*/}
                    {/*<Text> send cmd</Text>*/}
                {/*</TouchableOpacity>*/}
                {/*/!*<TouchableOpacity onPress={()=>this.props.navigation.navigate("TestTcp")}*!/*/}
                {/*/!*style={{height:50,width:120,backgroundColor:'#eeeeee',alignItems:'center',justifyContent:'center',margin:5}}>*!/*/}
                {/*/!*<Text> 跳转到下一测试页面</Text>*!/*/}
                {/*/!*</TouchableOpacity>*!/*/}
                {/*<TouchableOpacity onPress={this.testtest.bind(this)}*/}
                                  {/*style={{height:50,width:120,backgroundColor:'#eeeeee',alignItems:'center',justifyContent:'center',margin:5}}>*/}
                    {/*<Text> TESTTEST</Text>*/}
                {/*</TouchableOpacity>*/}
                {/*<ScrollView>*/}
                    {/*{this.chatter.map((msg, index) => {*/}
                        {/*return (*/}
                            {/*<Text key={index}>*/}
                                {/*{msg}*/}
                            {/*</Text>*/}
                        {/*);*/}
                    {/*})}*/}
                {/*</ScrollView>*/}

            </View>)
    }
}


const
    styles = StyleSheet.create({
        container: {
            flex: 1,
            backgroundColor: 'white',
            alignItems: 'center'

        }


    });
